//
//  XRRadioView.m
//  Auditory
//
//  Created by 寒竹子 on 15/5/6.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//

/**
 *  @brief   音乐播放
 *  @author  寒竹子
 */

#define kBorder       10.0f
#define kBottomBorder 10.0f
#define KImageBorder  60.0f
#define kNavgation_H  64.0f
#define KButton_W     56.0f
#define KButton_H     48.0f

// 播放器播放状态发生变化的通知
#define KNotification_PlayerStateChanged @"PlayerStateChangedNotification"

#import "XRRadioView.h"
#import "FSPlaylistItem.h"
#import "Globle.h"
#import "songListModel.h"
#import "MusicModel.h"
#import "FSAudioStream.h"
#import "UIImageView+WebCache.h"
#import "AudioListDetailCell.h"
#import "AudioToolBar.h"

@interface XRRadioView ()<
                            AudioToolBarDelegate,
                            UIScrollViewDelegate,
                            UITableViewDataSource,
                            UITableViewDelegate
                        >

@property (nonatomic, strong) CADisplayLink * link;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) AudioToolBar * audiotoolBar;
@property (nonatomic, strong) Globle * globle;

@end

@implementation XRRadioView
{
    UIScrollView * _topScrollView; // 上部滚动的view
    UIPageControl * _pageControl;   // 指示器
    UILabel * _singner;            // 演唱者
    
    UIImageView * _imageView;
    UILabel * _titleView;
    NSInteger _currentPage;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置背景颜色
        self.backgroundColor = RGB(250, 250, 250, 1.0f);
        
        // 数据源
        _dataArray = [[NSMutableArray alloc] init];
        
        NSDictionary * dict1 = @{@"singnerURL":@"", @"singner":@"王舰"};
        NSDictionary * dict2 = @{@"channelURL":@"", @"channelTitle":@"BOSS开讲"};
        
        [_dataArray addObject:dict1];
        [_dataArray addObject:dict2];
        
        // 监听进入后台
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackgroundControlRadioState:) name:XRRadioViewStatusNotifiCation object:nil];
        
        // 播放器
        audioPlayer = [AudioPlayer sharedAudioPlayer];
        audioPlayer.delegate = self;
        
        // 播放迷你条
        _audiotoolBar = [AudioToolBar sharedAudioToolBarWithFrame:CGRectZero];
        _audiotoolBar.delegate = self;
        
        // 全局属性
        _globle = [Globle sharedGloble];
        
        /*
            头部导航View
         */
        UIButton * navView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, kNavgation_H)];
        [navView setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forState:UIControlStateNormal];
        [navView setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forState:UIControlStateHighlighted];
        [self addSubview:navView];
        
        // 添加返回按钮
        UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, (kNavgation_H - 30.0f) / 2.0f + 8.0f, 30.0f, 30.0f)];
        [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:backBtn];
        
        _titleView = [[UILabel alloc] initWithFrame:CGRectMake((frame.size.width - 200.0f) / 2.0f, (kNavgation_H - 30.0f) / 2.0f + 8.0f, 200.0f, 30.0f)];
        _titleView.textAlignment = NSTextAlignmentCenter;
        _titleView.font = TextFont(17.0f);
        _titleView.textColor = RGB(50, 50, 50, 1.0f);
        [self addSubview:_titleView];
        
        // 默认是第二页
        _currentPage = 1;
        
        /*
         上部滚动的scrollView
         */
        _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kNavgation_H, frame.size.width, frame.size.height - 280.0f)];
        _topScrollView.backgroundColor = RGB(250, 250, 250, 1.0f);
        
        _topScrollView.pagingEnabled = YES;
        _topScrollView.bounces = NO;
        _topScrollView.showsHorizontalScrollIndicator = NO;
        _topScrollView.showsVerticalScrollIndicator = NO;
        _topScrollView.contentSize = CGSizeMake(frame.size.width * 2.0f, _topScrollView.frame.size.height);
        _topScrollView.contentOffset = CGPointMake(frame.size.width * _currentPage, 0);
        _topScrollView.delegate = self;
        [self addSubview:_topScrollView];
        
        // layout 底部的按钮
        NSArray * imageArr = @[@"comment-gray", @"like-gray", @"share-gray", @"list-gray"];
        CGFloat xborder = (frame.size.width - KButton_W * 4.0f) / 5.0f;
        for (int i = 0; i < imageArr.count; i++) {
            CGFloat btnX = xborder + (xborder + KButton_W) * i;
            UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, frame.size.height - KButton_H - kBottomBorder, KButton_W, KButton_H)];
            btn.tag = 2001 + i;
            [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btn];
        }
        
        // 播放按钮
        _playButton = [[UIButton alloc] initWithFrame:CGRectMake((frame.size.width - kNavgation_H) / 2.0f, self.frame.size.height - kNavgation_H - KButton_H - kBottomBorder, 64, 64)];
        [_playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [_playButton addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_playbackButton setBackgroundColor:[UIColor cyanColor]];
        [self addSubview:_playButton];
        
        // 上一首
        _preButton = [[UIButton alloc] initWithFrame:CGRectMake(_playButton.frame.origin.x - 48 - 20, _playButton.frame.origin.y + 8, 48, 48)];
        [_preButton setImage:[UIImage imageNamed:@"pre"] forState:UIControlStateNormal];
        
        [_preButton addTarget:self action:@selector(preAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_preButton];
        
        // 下一首
        _nextButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_playButton.frame) + 20, _playButton.frame.origin.y + 8, 48, 48)];
        [_nextButton setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
        
        [_nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_nextButton];
        
        // 当前播放进度显示
        _currentPlayBackTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, _playButton.frame.origin.y - 25.0f, 40.0f, 25.0f)];
        _currentPlayBackTimeLabel.font = TextFont(13.0f);
        _currentPlayBackTimeLabel.textAlignment = NSTextAlignmentLeft;
        _currentPlayBackTimeLabel.textColor = RGB(0, 0, 0, 1.0f);
        _currentPlayBackTimeLabel.text = @"00:00";
        
        [self addSubview:_currentPlayBackTimeLabel];
        
        // 进度显示
        progress = [[UISlider alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_currentPlayBackTimeLabel.frame), _currentPlayBackTimeLabel.frame.origin.y + 3, self.frame.size.width - 100, 20.0f)];
        progress.continuous = YES;
        progress.minimumTrackTintColor = RGB(249, 16, 42, 1.0f);
        progress.maximumTrackTintColor = RGB(200, 200, 200, 1.0f);
        [progress setThumbImage:[UIImage imageNamed:@"player-progress-point-h"] forState:UIControlStateNormal];
        
        [progress addTarget:self action:@selector(seek) forControlEvents:UIControlEventValueChanged];
        
        [self addSubview:progress];
        
        // 重新设置ScrollView的frame
        CGFloat scrollHeight = progress.frame.origin.y - kBorder - kNavgation_H;
        CGRect scrollFrame = _topScrollView.frame;
        scrollFrame.size.height = scrollHeight;
        _topScrollView.frame = scrollFrame;
        
        // 设置 歌手 和 专辑图片的frame
        // 显示头像
        CGFloat headWidth = 0.0f;
        if (iPhone4S) {
            headWidth = self.frame.size.width - KImageBorder * 2.0f - 20.0f;
        }else if (iPhone5S) {
            headWidth = self.frame.size.width - KImageBorder * 2.0f;
        }else if (iPhone6) {
            headWidth = self.frame.size.width - KImageBorder * 2.0f + 20.0f;
        }else {
            headWidth = self.frame.size.width - KImageBorder * 2.0f + 30.0f;
        }
        
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(frame.size.width * _currentPage + (self.frame.size.width - headWidth) / 2.0f, (_topScrollView.frame.size.height - headWidth) / 2.0f, headWidth, headWidth)];
        _imageView.layer.masksToBounds = YES;
        _imageView.layer.cornerRadius = _imageView.frame.size.height / 2.0f;
        _imageView.layer.borderWidth = 4.0f;
        _imageView.layer.borderColor = RGB(80, 80, 80, .6f).CGColor;
        _imageView.image = [UIImage imageNamed:@"headDefault"];
        [_topScrollView addSubview:_imageView];
        
        // 显示歌手
        _singner = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width * _currentPage, (_imageView.frame.origin.y - 20.0f) / 2.0f, frame.size.width, 20.0f)];
        _singner.font = TextFont(14.0f);
        _singner.textColor = RGB(80, 80, 80, 1.0f);
        _singner.textAlignment = NSTextAlignmentCenter;
        _singner.text = @"— 刀郎 —";
        [_topScrollView addSubview:_singner];
        
        /*
            初始化tableView
         */
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, _topScrollView.frame.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = RGB(250, 250, 250, 1.0f);
        _tableView.separatorColor = RGB(220, 220, 220, 1.0f);
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        [_topScrollView addSubview:_tableView];
        
        // 添加page指示器
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_imageView.frame) + (_topScrollView.frame.size.height - CGRectGetMaxY(_imageView.frame) - 20.0f) / 2.0f + kNavgation_H, frame.size.width, 20.0f)];
        _pageControl.numberOfPages = 2;
        _pageControl.pageIndicatorTintColor = RGB(220, 220, 220, 1.0f);
        _pageControl.currentPageIndicatorTintColor = RGB(150, 150, 150, 1.0f);
        _pageControl.currentPage = _currentPage;
        [_pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:_pageControl];
        
        // 音乐总时间
        _totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(progress.frame.size.width + progress.frame.origin.x, _currentPlayBackTimeLabel.frame.origin.y, 40.0f, 25.0f)];
        _totalTimeLabel.font = TextFont(13.0f);
        _totalTimeLabel.textColor = RGB(0, 0, 0, 1.0f);
        _totalTimeLabel.textAlignment = NSTextAlignmentRight;
        _totalTimeLabel.text = @"00:00";
        [self addSubview:_totalTimeLabel];
        
        [self updateHeaderRatation];
    }
    
    return self;
}

/**
 * @brief  CADisplayLink
 *
 * @param
 *
 * @return
 */
- (CADisplayLink *)link
{
    if (nil == _link) {
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLink)];
    }
    
    return _link;
}

/**
 * @brief  16s转一圈  22.5度/s
 *
 * @param
 *
 * @return
 */
- (void)updateLink
{
    // 1/60s * 22.5度
    // 规定时间转动的速度 = 时间 * 速度
    CGFloat angle = _link.duration * M_PI_4 / 2.0f;
    _imageView.transform = CGAffineTransformRotate(_imageView.transform, angle);
}

/**
 * @brief  返回
 *
 * @param
 *
 * @return
 */
- (void)backAction
{
    if (self.callBlock) {
        self.callBlock();
    }
}

/**
 * @brief  更新头像状态
 *
 * @param
 *
 * @return
 */
- (void)updateHeaderRatation
{
    if (isPlaying) {
        // 正在播放
        [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    }else {
        // 停止播放
        [self.link invalidate];
        self.link = nil;
    }
}

/**
 * @brief  启动定时器
 *
 * @param
 *
 * @return
 */
- (void)startTimer
{
    _progressUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:.8f target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:_progressUpdateTimer forMode:NSRunLoopCommonModes];
}

/**
 * @brief  更新进度条
 *
 * @param
 *
 * @return
 */
- (void)updateProgress
{
    if (!audioPlayer || audioPlayer.duration == 0) {
        progress.value = 0.0f;
        _currentPlayBackTimeLabel.text = [self timeFormatWithSecconds:progress.value];
        return;
    }
    
    progress.minimumValue = 0.0f;
    progress.maximumValue = audioPlayer.duration;
    progress.value = audioPlayer.progress;
    
    _globle.progress = progress.value / progress.maximumValue;
    
    _currentPlayBackTimeLabel.text = [self timeFormatWithSecconds:audioPlayer.progress];
}

/**
 * @brief  停止一切事件
 *
 * @param
 *
 * @return
 */
- (void)stopEverything
{
    isPlaying = NO;
    [audioPlayer stop];
    
    // 停止头像转动
    [self.link invalidate];
    self.link = nil;
    
    // 将head的位置复位
    _imageView.transform = CGAffineTransformIdentity;
    
    [_progressUpdateTimer invalidate];
    _progressUpdateTimer = nil;
}

/**
 * @brief  设置选中的资源进行播放
 *
 * @param
 *
 * @return
 */
- (void)setSeletedPlayItem:(FSPlaylistItem *)seletedPlayItem
{
    if (_seletedPlayItem != seletedPlayItem) {
        _seletedPlayItem = seletedPlayItem;
        
        // 设置标题 和 歌手头像
        _titleView.text = seletedPlayItem.title;
        
        [_imageView setImage:[UIImage imageNamed:@"headDefault"]];
        
        [self stopEverything]; // 停止一切事件
        
        _totalTimeLabel.text = [self timeFormatWithSecconds:[_model.duration intValue]];
        
        // 1s后切换到下一首音乐
        sleep(1.0f);
        [self startMusicAction];
    }
}

/**
 * @brief  开始播放
 *
 * @param
 *
 * @return
 */
- (void)startMusicAction
{
    // 开始播放音乐
    [self startMusic];
    [self startTimer];
}

/**
 * @brief  开始播放音乐
 *
 * @param
 *
 * @return
 */
- (void)startMusic
{
    [audioPlayer play:self.seletedPlayItem.url];
    
    [self updateHeaderRatation];
    [self updateControlsStatus];
}

/**
 * @brief  时间转换
 *
 * @param
 *
 * @return
 */
- (NSString *)timeFormatWithSecconds:(int)secconds
{
    // 得到分钟数
    int totalMinite = secconds / (60);
    int h = totalMinite / (60);
    int m = totalMinite % (60);
    int s = secconds % (60);
    
    if (h == 0) {
        return [NSString stringWithFormat:@"%02d:%02d", m, s];
    }else {
        return [NSString stringWithFormat:@"%02d:%02d:%02d", h, m, s];
    }
}

#pragma mark - 评论 / 收藏 / 分享 / 列表 Action

- (void)btnClick:(UIButton *)btn
{
    switch (btn.tag - 2000) {
        case 1:
        {
            // 评论
            if (_delegate && [_delegate respondsToSelector:@selector(radioViewCommentAction)]) {
                [_delegate radioViewCommentAction];
            }
        }
            break;
        case 2:
        {
            // 收藏
            if (_delegate && [_delegate respondsToSelector:@selector(radioViewLikeAction)]) {
                [_delegate radioViewLikeAction];
            }
        }
            break;
        case 3:
        {
            // 分享
            if (_delegate && [_delegate respondsToSelector:@selector(radioViewShareAction)]) {
                [_delegate radioViewShareAction];
            }
        }
            break;
        case 4:
        {
            // 列表
            if (_delegate && [_delegate respondsToSelector:@selector(radioViewListAction)]) {
                [_delegate radioViewListAction];
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - private

/**
 * @brief  显示成功或者失败的信息 delay (s)
 *
 * @param
 *
 * @return
 */
- (void)showHudWithHint:(NSString *)hint delay:(int)timeDelay
{
    // 创建Hud
    MBProgressHUD * progressHud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)];
    progressHud.labelFont = TextFont(18.0f);
    progressHud.labelColor = [UIColor redColor];
    progressHud.labelText = hint;
    progressHud.mode = MBProgressHUDModeText; // 只显示文字
    progressHud.animationType = MBProgressHUDAnimationZoom;
    progressHud.removeFromSuperViewOnHide = YES;
    [self addSubview:progressHud];
    [progressHud show:YES];
    
    [progressHud hide:YES afterDelay:timeDelay];
}

/**
 * @brief  播放
 *
 * @param
 *
 * @return
 */
- (void)playButtonAction
{
    // 判断是否有可用的播放资源
    if (!_globle.isHasResource) {
        NSLog(@"没有可供播放的资源");
        
        return;
    }
    
    // 主线程中更新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        // 判断是否正在播放
        if (isPlaying) {
            isPlaying = NO;
        }else {
            isPlaying = YES;
        }
        
        // 当前处于暂停状态
        if (audioPlayer.state == AudioPlayerStatePaused) {
            [audioPlayer resume]; // 恢复播放
            
            [self startTimer]; // 启动定时器
        }else {
            [audioPlayer pause]; // 暂停播放
            [_progressUpdateTimer invalidate];
        }
        
        [self updateHeaderRatation];
        
        [_playButton setImage:(isPlaying? [UIImage imageNamed:@"pause"] : [UIImage imageNamed:@"play"]) forState:UIControlStateNormal];
        // 发送通知 更改播放按钮的状态
        _globle.isPlaying = isPlaying;
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotification_PlayerStateChanged object:nil];
    });
}

/**
 * @brief  上一首
 *
 * @param
 *
 * @return
 */
- (void)preAction:(UIButton *)btn
{
    [self stopEverything];
    
    if (_delegate && [_delegate respondsToSelector:@selector(radioView:preSwitchMusic:)]) {
        [_delegate radioView:self preSwitchMusic:btn];
    }
}

/**
 * @brief  下一首
 *
 * @param
 *
 * @return
 */
- (void)nextAction:(UIButton *)btn
{
    [self stopEverything];
    
    if (_delegate && [_delegate respondsToSelector:@selector(radioView:nextSwitchMusic:)]) {
        [_delegate radioView:self nextSwitchMusic:btn];
    }
}

/**
 * @brief  当应用进入后台处理事件
 *
 * @param
 *
 * @return
 */
- (void)applicationEnterBackgroundControlRadioState:(NSNotification *)nf
{
    NSDictionary * dict = [nf userInfo];

    // 取出信息
    NSString * InfoStr = [dict objectForKey:@"keyStatus"];
    
    // 暂停
    if ([InfoStr isEqualToString:@"UIEventSubtypeRemoteControlPause"]) {
        [self playButtonAction];
    }else if ([InfoStr isEqualToString:@"UIEventSubtypeRemoteControlPlay"]) {
        // 播放
        [self playButtonAction];
    }else if ([InfoStr isEqualToString:@"UIEventSubtypeRemoteControlPreviousTrack"]) {
        // 上一首
        [self preAction:_preButton];
    }else if ([InfoStr isEqualToString:@"UIEventSubtypeRemoteControlNextTrack"]) {
        // 下一首
        [self nextAction:_nextButton];
    }
}

/**
 * @brief  进度拖动
 *
 * @param
 *
 * @return
 */
- (void)seek
{
    if (!audioPlayer) {
        return;
    }
    
    [audioPlayer seekToTime:progress.value];
    _globle.progress = progress.value / progress.maximumValue;
    
    // 显示拖动的进度
    _currentPlayBackTimeLabel.text = [self timeFormatWithSecconds:progress.value];
}

/**
 * @brief  更新状态
 *
 * @param
 *
 * @return
 */
- (void)updateControlsStatus
{
    if (audioPlayer.state == AudioPlayerStateStopped) {
        // 若正在播放 则按 顺序/随机/单曲 播放 切换歌曲
        
        if (isPlaying) {
            // playType 随机 顺序 单曲
            if (_delegate && [_delegate respondsToSelector:@selector(radioView:musicStop:)]) {
                [_delegate radioView:self musicStop:playType];
            }
        }
        isPlaying = NO;
        NSLog(@"播放停止");
    }else if (audioPlayer.state == AudioPlayerStateReady) {
        NSLog(@"播放已经准备好");
    }else if (audioPlayer.state == AudioPlayerStateRunning) {
        NSLog(@"播放正在运行");
    }else if (audioPlayer.state == AudioPlayerStatePlaying) {
        isPlaying = YES;
        NSLog(@"正在播放");
    }else if (audioPlayer.state == AudioPlayerStateError) {
        NSLog(@"播放错误");
    }else if (audioPlayer.state == AudioPlayerStateDisposed) {
        
    }
    
    // 主线程中更新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateHeaderRatation];
        
        if (isPlaying) {
            // 正在播放
            [_playButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        }else {
            // 停止/暂停播放
            [_playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        }
        
        // 发送通知 更改播放按钮的状态
        _globle.isPlaying = isPlaying;
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotification_PlayerStateChanged object:nil];
    });
}

#pragma mark - AudioPlayerDelegate

/**
 * @brief  播放状态发生变化
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer stateChanged:(AudioPlayerState)state
{
    [self updateControlsStatus];
}

/**
 * @brief  当前播放发生错误
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer didEncounterError:(AudioPlayerErrorCode)errorCode
{
    [self updateControlsStatus];
}

/**
 * @brief  取消播放
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems
{
    [self updateControlsStatus];
}

/**
 * @brief  缓冲完成
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    [self updateControlsStatus];
}

/**
 * @brief  播放完成
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(AudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    // 播放完成
    [self updateControlsStatus];
}

/**
 * @brief  开始播放
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    [self updateControlsStatus];
}

- (void)audioPlayer:(AudioPlayer *)audioPlayer logInfo:(NSString *)line
{
    [self updateControlsStatus];
}

/**
 * @brief  播放网络状态发生变化
 *
 * @param
 *
 * @return
 */
- (void)audioPlayer:(AudioPlayer *)audioPlayer internalStateChanged:(AudioPlayerInternalState)state
{
    /*
        音频处理：
            1. 等待从网络加载数据
            2. 等待队列开始播放
            3. 开始播放
            4. 缓冲
     */
    
    switch (state) {
        case AudioPlayerInternalStateDisposed:
        {
            NSLog(@"NetState:开始处理");
        }
            break;
        case AudioPlayerInternalStateError:
        {
            NSLog(@"NetState:网络错误");
        }
            break;
        case AudioPlayerInternalStateInitialised:
        {
            
        }
            break;
        case AudioPlayerInternalStatePaused:
        {
            // 暂停
            NSLog(@"NetState:暂停");
        }
            break;
        case AudioPlayerInternalStatePlaying:
        {
            // 播放
            NSLog(@"NetState:播放");
        }
            break;
        case AudioPlayerInternalStateRebuffering:
        {
            // 缓冲
            NSLog(@"NetState:缓冲中...");
        }
            break;
        case AudioPlayerInternalStateRunning:
        {
            NSLog(@"NetState:运行中...");
        }
            break;
        case AudioPlayerInternalStateStartingThread:
        {
            
        }
            break;
        case AudioPlayerInternalStateStopped:
        {
            // 停止播放
            NSLog(@"NetState:停止播放");
        }
            break;
        case AudioPlayerInternalStateStopping:
        {
            NSLog(@"NetState:停止中...");
        }
            break;
        case AudioPlayerInternalStateWaitingForData:
        {
            // 等待从网络获取数据
            NSLog(@"NetState:等待从网络加载数据");
        }
            break;
        case AudioPlayerInternalStateWaitingForQueueToStart:
        {
            // 1. 等待从网络加载数据
            // 2. 等待队列开始播放
            // 3. 开始播放
            // 4. 缓冲
            NSLog(@"NetState:等待队列开始播放");
        }
            break;
        default:
        {
            NSLog(@"NetState:未知错误");
        }
            break;
    }
}

/**
 * @brief  pageControl值改变
 *
 * @param
 *
 * @return
 */
- (void)pageChanged:(UIPageControl *)page
{
    _currentPage = page.currentPage;
    [_topScrollView setContentOffset:CGPointMake(_topScrollView.frame.size.width * _currentPage, 0) animated:YES];
}

#pragma mark - UItableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"AudioListDitailellID";
    
    AudioListDetailCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[AudioListDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    // 禁止cell点击
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexPath = indexPath;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70.0f;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;
    _pageControl.currentPage = _currentPage;
}

#pragma mark - AudioToolBarDelegate

- (void)playAudioWithButtonState:(BOOL)isPlaying
{
    // 手动调用播放Action
    [self playButtonAction];
}

@end
